package thinkinjava4.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;

public class OSExecute {
    public static final String DEFAULT_DIR = "out\\production\\workspace";
    public static final String ATUNIT_ANN = "java thinkinjava4.atunit.AtUnit thinkinjava4\\ch20_annotations\\";

    public static void command(String command) {
        boolean err = false;
        try {
            Process process = new ProcessBuilder(command.split(" ")).start();
            BufferedReader results = new BufferedReader(new InputStreamReader(process.getInputStream(), "GBK"));
            String s;
            while ((s = results.readLine()) != null)
                System.out.println(s);
            BufferedReader errors = new BufferedReader(new InputStreamReader(process.getErrorStream(), "GBK"));
            while ((s = errors.readLine()) != null) {
                System.err.println(s);
                err = true;
            }
        } catch (Exception e) {
            if (!command.startsWith("CMD /C"))
                command("CMD /C " + command);
            else
                throw new RuntimeException(e);
            if (err)
                throw new OSExecuteException("Errors executing " + command);
        }
    }

    /**
     * @param dir     设置命令工作目录
     * @param command
     */
    public static void command(String dir, String command) {
        boolean err = false;
        try {
            ProcessBuilder builder = new ProcessBuilder(command.split(" "));
            builder.directory(new File(dir));
            Process process = builder.start();
            BufferedReader results = new BufferedReader(new InputStreamReader(process.getInputStream(), "GBK"));
            String s;
            while ((s = results.readLine()) != null)
                System.out.println(s);
            BufferedReader errors = new BufferedReader(new InputStreamReader(process.getErrorStream(), "GBK"));
            while ((s = errors.readLine()) != null) {
                System.err.println(s);
                err = true;
            }
        } catch (Exception e) {
            if (!command.startsWith("CMD /C"))
                command("CMD /C " + command);
            else
                throw new RuntimeException(e);
            if (err)
                throw new OSExecuteException("Errors executing " + command);
        }
    }
}
